import UsersApi from "../api/user";
import router from "@/router";

import axios, {
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
  Method
} from "axios";
import { Message } from "element-ui";
import { cloneDeep } from "lodash";

let baseURL;
// 环境变量配置接口地址
switch (process.env.NODE_ENV) {
  case "production":
    baseURL = "http://localhost:8080/";
    break;
  // case "test":
  //   httpURL = TEST_URL;
  // break;
  case "development":
    baseURL = "api/";
    break;
  default:
    baseURL = "http://localhost:8080/";
}

const axiosInstance = axios.create({
  baseURL,
  timeout: 30000
});

// axios请求拦截
axiosInstance.interceptors.request.use(config => {
  // 此处若使用引入的header会出现错误，暂未找到解决方案
  config.headers = {
    "api-version": "1.0",
    Authorization: " "
  };
  return config;
});
// axiosInstance.interceptors.request.use(function(config) {
//   const token = UsersApi.getToken();
//   // config.headers["api-version"] = "1.0";
//   config.headers["Authorization"] = "";
//   // config.headers["Content-Type"] = "multipart/form-data";
//   if (config.headers["Content-Type"] == "multipart/form-data") {
//     config.headers["Content-Type"] = "multipart/form-data";
//     config.headers.post["Content-Type"] = "multipart/form-data";
//   }
//   !!token && (config.headers["Authorization"] = `Bearer ${token}`);
//   return config;
// });
//请求返回拦截，把数据返回到页面之前做些什么...、
// axios.defaults.withCredentials = true;

axiosInstance.interceptors.response.use(
  response => {
    //特殊错误处理，状态为10时为登录超时
    if (response.data.code == "-1000") {
      router.push("/login");
      return Promise.reject("登录已超时");
      //其余错误状态处理
    } else if (response.data.code == "-1001") {
      return Promise.reject("无权限");
    } else {
      //将我们请求到的信息返回页面中请求的逻辑
      return response;
    }
    //......
  },
  function(error) {
    return Promise.reject(error);
  }
);

// http请求类
class HttpRequest {
  /**
   * @description:请求主函数
   * @param {AxiosRequestConfig} axiosRequestConfig 请求参数
   * @return {Promise<any>} 响应结果，为Promise<any>或false
   */
  request = async axiosRequestConfig => {
    let {
      url,
      data,
      params,
      method,
      responseType = "text"
    } = axiosRequestConfig;
    let result;
    try {
      result = await axiosInstance({
        url,
        method,
        params,
        data,
        responseType
      });
    } catch (err) {
      Message({
        message: err,
        type: "error",
        center: true
      });
      result = false;
    }
    return result;
  };

  // get请求
  get = (url, params = {}) => {
    return this.request({
      url,
      params,
      method: "get"
    });
  };

  // post请求
  post = (url, data = {}) => {
    return this.request({
      url,
      data,
      method: "post"
    });
  };

  // put请求
  put = (url, data = {}) => {
    return this.request({
      url,
      data,
      method: "put"
    });
  };

  // delete请求
  delete = (url, params = {}) => {
    return this.request({
      url,
      params,
      method: "delete"
    });
  };

  // 使用axios组件手动上传文件
  uploadFile = (url, params) => {
    let formData = new FormData();
    Object.entries(params).forEach(item => {
      formData.append(item[0], item[1]);
    });
    return this.request({
      url,
      data: formData,
      method: "post",
      headers: { "Content-Type": "multipart/form-data" }
    });
  };

  // 获取blob格式的数据
  getBlob = (url, params = {}, method = "get") => {
    return this.request({
      url,
      params,
      data: params,
      method,
      responseType: "blob"
    });
  };

  // 导出电子表格方法，封装默认参数为 1页5000条
  export = (url, params = {}) => {
    // 如params对象不包含 exportPage ，则默认为导出五千条
    let { exportPage } = params;
    let initialExportPage = exportPage || { pageNo: 1, pageSize: 5000 };
    let data = cloneDeep({ ...params, ...initialExportPage });
    return this.request({
      url,
      data,
      method: "post",
      responseType: "blob"
    });
  };
}

const httpRequest = new HttpRequest();

export default httpRequest;
